package com.wfcm.controller;

import com.wfcm.annotation.IgnoreToken;
import com.wfcm.entity.WfNewMessageEntity;
import com.wfcm.service.WfNewMessageService;
import com.wfcm.utils.ISsoLoginHelper;
import com.wfcm.utils.PageUtils;
import com.wfcm.utils.Query;
import com.wfcm.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/message")
public class MessageController {


    @Autowired
    private WfNewMessageService newMessageService;

    @RequestMapping("/newFlag")
    public R newFlag(HttpServletRequest req){

        Integer userId = ISsoLoginHelper.confirm(req);
        if(0 == newMessageService.newFlag(userId)){
            return R.ok().put("newFlag",0);//没有新消息
        }
        return R.ok().put("newFlag",1);
    }


    @RequestMapping("/queryMessage")
    @IgnoreToken
    @ResponseBody
    public R queryMessage(HttpServletRequest req){

        Integer userId = ISsoLoginHelper.confirm(req);
        if(userId==null){
            return R.ok();
        }
        Integer total =  newMessageService.queryTotal(userId);

        Map map = new HashMap<String,Object>();
        map.put("page",req.getParameter("page"));
        Query query =  new Query(map);
        query.put("userId",userId);
        List<WfNewMessageEntity> messagelist =  newMessageService.queryMessage(query);

        PageUtils pageUtils = new PageUtils(messagelist,total,query.getLimit(),query.getPage());

        return R.ok().put("pageUtils",pageUtils);
    }

    @RequestMapping("/update")
    @ResponseBody
    public R update(HttpServletRequest req){

        Integer userId = ISsoLoginHelper.confirm(req);

        WfNewMessageEntity newMessageEntity = new WfNewMessageEntity();

        String messageId = req.getParameter("messageId");
        String[] messageIdArr = messageId.split(",");
        for(int i=0 ; i<messageIdArr.length; i++) {
            newMessageEntity.setUserId(userId);
            newMessageEntity.setId(Integer.valueOf(messageIdArr[i]));
            newMessageService.update(newMessageEntity);
        }
        return R.ok();
    }

    @RequestMapping("/deleteList")
    @ResponseBody
    public R deleteList(HttpServletRequest req){

        Integer userId = ISsoLoginHelper.confirm(req);

        String messageId = req.getParameter("messageId");
        String[] messageIdArr = messageId.split(",");
        for(int i=0 ; i<messageIdArr.length; i++) {
            newMessageService.delete(Integer.valueOf(messageIdArr[i]));
        }
        return R.ok();
    }

}
